
/*
 * WON Script
 * http://code.google.com/p/w-o-n/
 *
 * Copyright (c) 2009 WON
 * licensed under the MIT (MIT-LICENSE.txt)
 */

//setup the basics
var globalMap = new function() {
  
  var myMap; //new map
  var tools; //utility
  
  function loadData(type,notice) { //private - load 
    $.ajax({
      beforeSend: function() { $('#extra p:eq('+notice+')').show(); },
      complete: function() { $('#extra p:eq('+notice+')').hide(); },
      type: "GET",
      url: "wallornot-load.php",
      data: "request="+type,
      dataType: "xml",
      success: function(data){
        $("marker",data).each(function(i) {
          if(type !== 'service') {
            //new DOMs on every iteration - not optimal
            var m = document.createElement('div');
            var ts = $(this).find('ts').text();
            var msg = $(this).find('cmt').text();
            var lat = $(this).find('lat').text();
            var lng = $(this).find('lng').text();
            var typ = $(this).find('typ').text();
            var val = $(this).find('val').text();
            var vna = $(this).find('vna').text();
            //alert(ts+','+msg+','+lat+','+lng+','+typ+','+val);
            $(m).attr('id','mark'+ts).append('<img src="images/'+val+'.png" alt="'+val+'" style="position:relative; top:-30px; left:-6px;" />').click(function(e) { popMessage(ts,typ,val,vna,msg,e.pageY-30+"px",e.pageX+30+"px"); }); //jquery method
            myMap.overlayLayer.addElement(m, lat, lng); // element, latitude, longitude
            myMap.redraw();
          } else {
            $('#serviceType select').append('<option id="s'+$(this).find('tid').text()+'">'+$(this).find('typ').text()+'</option>');
          }
        }); 
      }
    });
  }
  
  function popMessage(time,type,value,word,comment,ax,ay) { //private - generate accessible message
    //alert(time+','+type+','+value+','+comment+','+ax+','+ay);
    $('.message').remove();
    $('#wrap').append('<div class="message"><h3>'+type+' : '+value+' '+word+'</h3><p>'+comment+'</p></div>');
    $('.message').css({'top':ax,'left':ay}).fadeOut(10000);
  }
  
  return {
		init : function () { //public

			myMap = new Mapiator.Map('map');
			myMap.setZoomLevel(4);
			myMap.setCenter(36, 106);

      tools = Mapiator.util;

      myMap.getTileUrl = function(x, y, zoom){
        // default map server
        return 'http://mt1.google.com/vt/v=ap.97&hl=zh-CN&x='+x+'&y='+y+'&z='+zoom;
      };

      //choose map server
      $('#toggleMap p span:eq(0)').click(
                function() {
                  myMap.getTileUrl = function(x, y, zoom){
                    // return url for Open Street Map tile:
                    return 'http://b.tile.openstreetmap.org/'+zoom+'/'+x+'/'+y+'.png';
                  }
                  myMap.redraw();
                  return false;
                });
      $('#toggleMap p span:eq(1)').click(
                function() {
                  myMap.getTileUrl = function(x, y, zoom){
                    // return url for Google.com Map tile:
                    return 'http://mt0.google.com/vt/v=ap.97&hl=zh-CN&x='+x+'&y='+y+'&z='+zoom;
                  }
                  myMap.redraw();
                  return false;
                });
      $('#toggleMap p span:eq(2)').click(
                function() {
                  myMap.getTileUrl = function(x, y, zoom){
                    // return url for Google.com Map tile:
                    return 'http://mt1.google.com/vt/v=ap.97&hl=zh-CN&x='+x+'&y='+y+'&z='+zoom;
                  }
                  myMap.redraw();
                  return false;
                });
      $('#toggleMap p span:eq(3)').click(
                function() {
                  myMap.getTileUrl = function(x, y, zoom){
                    // return url for Google.com Map tile:
                    return 'http://mt2.google.com/vt/v=ap.97&hl=zh-CN&x='+x+'&y='+y+'&z='+zoom;
                  }
                  myMap.redraw();
                  return false;
                });
      
      loadData('service',1);
      loadData('pre',0);
			myMap.redraw();
		},
    addMark : function (type,ax,ay) {
      
      //new DOMs on every iteration - not optimal
      var w = document.getElementById('map').offsetWidth;
      var h = document.getElementById('map').offsetHeight;
      var extend = 256 * (1<<myMap.getZoom());
      var playground = new tools.VisibleArea(myMap.getLat(), myMap.getLng(), extend, w, h);
      var cood = ax ? playground.latLngAt(ax, ay) : playground.centerLatLng();
      
      var marker = document.createElement('div');
      $(marker).attr('class','mark'+type.attr('alt')).append('<img src="'+type.attr('src')+'" alt="'+type.attr('alt')+'" title="'+type.attr('title')+'" style="position:relative; top:-30px; left:-6px;" />');
      myMap.overlayLayer.addElement(marker, cood[0], cood[1]); // latitude, longitude
      
      var vid;
      var sid = $('#serviceType option:selected').attr('id').replace(/s/,"");
      var ser = $('#serviceType option:selected').text();
      var cmt = $('#cmtExtra textarea').val();
      if(type.attr('alt') == 'ok') vid = 1;
      if(type.attr('alt') == 'blocked') vid = 2;
      if(type.attr('alt') == 'unstable') vid = 3;
      if(type.attr('alt') == 'redirected') vid = 4;
      
      $.post("wallornot-create.php", { lat: cood[0], lng: cood[1], service: sid, status: vid, comment: cmt }, function(data){
        if(data.indexOf('saved') > 0) {
          $('.message').remove();
          $('#wrap').append('<div class="message"><h3>'+ser+' : '+type.attr('alt')+'</h3><p>'+cmt+'</p></div>');
          $('.message').css({'top':ay,'left':ax+50}).fadeOut(10000);
        } else {
          $('.message').remove();
          $('#wrap').append('<div class="message"><p>'+data+'</p></div>');
          $('.message').css({'top':ay,'left':ax+50}).fadeOut(10000);
          $(marker).fadeOut(10000);
        }
      });
        
      myMap.redraw();
    },
    filterMark : function (type) {
      myMap.overlayLayer.removeElements(); //remove all elements
      if(type == parseFloat(type)) {
        loadData(type,0);
      } else if(type == 'new') {
        loadData('new',0);
      } else if(type == 'time') {
        loadData('time',0);
      } else if(type == 'affect') {
        loadData('affect',0);
      }
      myMap.redraw();
    },
    zIn : function (ax,ay) {
      myMap.zoomIn();
    },
    zOut : function (ax,ay) {
      myMap.zoomOut();
    }
  };
}

//run the application, adding listener
$(document).ready(function(){
  globalMap.init();
  
  //mouse wheel to zoom
  $('#map').bind('mousewheel', function(event, delta) {
    if (delta > 0) { globalMap.zIn(); }
    if (delta < 0) { globalMap.zOut(); }
  });
  
  //hide panel
  $('#fun').mouseenter(function(){ $(this).stop().fadeTo("fast", 1); }).mouseleave(function(){ $(this).stop().fadeTo("slow", 0.1); });
  $('#footer').mouseenter(function(){ $(this).stop().fadeTo("fast", 1); }).mouseleave(function(){ $(this).stop().fadeTo("slow", 0.1); });
  $('#footer a').attr('target','_blank');

  //filter markers
  $('#serviceType select').change(function() { globalMap.filterMark($('#serviceType option:selected').attr('id').replace(/s/,"")); });  
  
  //add marker types
  $('#markerType p img').draggable({
    appendTo: 'body',
    helper: 'clone',
    zIndex: 100,
    revert: true,
    stop: function(event,ui) {
      //globalMap.addMark(ui.helper.attr('alt'),ui.offset.left-1,ui.offset.top-4); //exact
      globalMap.addMark(ui.helper,ui.offset.left+6,ui.offset.top+30); //offset
    }
  });  
  
});